import type {RealTimeLog, ServerConfig, UpgradeHistory} from '@/type/toolLibs/protocol';
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useUpgradeStore = defineStore('upgrade', () => {
  // 服务器列表
  const servers = ref<ServerConfig[]>([
    {
      id: 'prod-app-01',
      name: '生产应用服务器-01',
      host: '192.168.1.101',
      port: 22,
      environment: 'production',
      description: '核心业务服务器'
    },
    {
      id: 'prod-app-02',
      name: '生产应用服务器-02',
      host: '192.168.1.102',
      port: 22,
      environment: 'production',
      description: '核心业务服务器'
    },
    {
      id: 'test-app-01',
      name: '测试服务器-01',
      host: '192.168.2.101',
      port: 22,
      environment: 'test',
      description: '功能测试环境'
    },
    {
      id: 'dev-app-01',
      name: '开发服务器-01',
      host: '192.168.3.101',
      port: 22,
      environment: 'development',
      description: '开发测试环境'
    }
  ]);

  // 实时日志
  const realTimeLogs = ref<RealTimeLog[]>([]);
  
  // 升级历史
  const upgradeHistory = ref<UpgradeHistory[]>([]);
  
  // 当前升级状态
  const upgradeStatus = ref<'idle' | 'uploading' | 'deploying' | 'completed' | 'failed'>('idle');
  
  // 计算属性
  const productionServers = computed(() => 
    servers.value.filter(s => s.environment === 'production')
  );
  
  const testServers = computed(() => 
    servers.value.filter(s => s.environment === 'test')
  );
  
  const developmentServers = computed(() => 
    servers.value.filter(s => s.environment === 'development')
  );

  // Actions
  const addLog = (log: RealTimeLog) => {
    realTimeLogs.value.push(log);
    // 保持最多1000条日志
    if (realTimeLogs.value.length > 1000) {
      realTimeLogs.value = realTimeLogs.value.slice(-1000);
    }
  };

  const clearLogs = () => {
    realTimeLogs.value = [];
  };

  const setUpgradeStatus = (status: typeof upgradeStatus.value) => {
    upgradeStatus.value = status;
  };

  const addUpgradeHistory = (history: UpgradeHistory) => {
    upgradeHistory.value.unshift(history);
  };

  return {
    servers,
    realTimeLogs,
    upgradeHistory,
    upgradeStatus,
    productionServers,
    testServers,
    developmentServers,
    addLog,
    clearLogs,
    setUpgradeStatus,
    addUpgradeHistory
  };
});